﻿using System;
using BuzzX8.Xmpp.StreamElements;
using BuzzX8.Xmpp.StreamElements.Stanza;

namespace BuzzX8.Xmpp.Connectivity
{
    public class XmppStream : IXmppStream
    {
        private IXmppChannel channel;

        public XmppStream(IXmppChannel channel)
        {
            if (channel == null) throw new NullReferenceException("channel");
            this.channel = channel;
        }

        public Stanza Read()
        {
            if (!channel.IsOpen) throw new InvalidOperationException();
            StreamElement receivedElement = null;

            do
            {
                receivedElement = channel.Receive();
                if (receivedElement is Stanza) return (Stanza)receivedElement;
                if (NonStanzaReceived != null) NonStanzaReceived(this, new NonStanzaReceivedEventArgs(receivedElement));
            } while (!(receivedElement is Stanza));

            throw new InvalidOperationException();
        }

        public void Write(Stanza element)
        {
            if (!channel.IsOpen) throw new InvalidOperationException();
            channel.Send(element);
        }

        public event EventHandler<NonStanzaReceivedEventArgs> NonStanzaReceived;
    }

    public class NonStanzaReceivedEventArgs : EventArgs
    {
        private StreamElement receivedElement;

        public NonStanzaReceivedEventArgs(StreamElement receivedElement)
        {
            if (receivedElement == null) throw new NullReferenceException("receivedElement");
            this.receivedElement = receivedElement;
        }

        public StreamElement ReceivedElement
        {
            get { return receivedElement; }
        }
    }
}
